package com.kingwang.study.spring.security.demo.security.handler;

import com.kingwang.study.spring.security.demo.security.dto.AuthenticationResult;
import com.kingwang.study.spring.security.demo.security.token.TokenBasedAuthenticationResultToken;
import com.kingwang.study.spring.security.demo.util.HttpServletUtils;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Token认证成功的处理器
 */
public class JsonResponseAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        if (!(authentication instanceof TokenBasedAuthenticationResultToken)) {
            HttpServletUtils.sendHttpStatusResponse(response, HttpStatus.UNAUTHORIZED);
        }

        TokenBasedAuthenticationResultToken tokenResult = (TokenBasedAuthenticationResultToken) authentication;

        AuthenticationResult result = new AuthenticationResult();
        result.setSuccess(true);
        result.setType(tokenResult.getTokenType());
        result.setToken(tokenResult.getToken());

        HttpServletUtils.sendJsonContentResponse(response, HttpStatus.OK, result);
    }
}
